<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
    >
      <el-form-item label="教育集团名称" prop="edgroup_id">
        <el-select
          v-model="queryParams.edgroup_id"
          style="width: 200px"
          :filterable="true"
          :clearable="true"
          @change="changeQueryEdgroup"
        >
          <el-option
            v-for="item in EdgroupList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item
        label="学校名称"
        prop="school_id"
        v-if="queryParams.edgroup_id"
      >
        <el-select
          v-model="queryParams.school_id"
          style="width: 200px"
          :filterable="true"
          :clearable="true"
          @change="changeQuerySchool"
        >
          <el-option
            v-for="item in schoolList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item
        label="班级名称"
        prop="class_id"
        v-if="queryParams.school_id"
      >
        <el-select
          v-model="queryParams.class_id"
          style="width: 200px"
          :filterable="true"
          :clearable="true"
        >
          <el-option
            v-for="item in classList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="网关MAC地址" prop="mac">
        <el-input
          v-model="queryParams.mac"
          placeholder="请输入网关MAC地址"
          clearable
          style="width: 200px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <!-- <el-form-item label="网关固件版本" prop="version">
        <el-input
          v-model="queryParams.version"
          placeholder="请输入网关固件版本"
          clearable
          style="width: 200px"
          @keyup.enter="handleQuery"
        />
      </el-form-item> -->
      <!-- <el-form-item label="在线时间" style="width: 308px">
        <el-date-picker
          v-model="queryParams.date"
          type="datetime"
          placeholder="选择日期时间"
          value-format="YYYY-MM-DD HH:mm:ss"
          default-time="12:00:00">
        </el-date-picker> -->
      <!-- <el-date-picker
          v-model="queryParams.date"
          type="datetimerange"
          range-separator="至"
          value-format="YYYY-MM-DD HH:mm:ss"
          start-placeholder="开始日期"
          end-placeholder="结束日期">
        </el-date-picker> -->
      <!-- </el-form-item> -->
      <el-form-item label="分布位置" prop="site">
        <el-select
          v-model="queryParams.site"
          placeholder="请选择分布位置"
          style="width: 260px"
          clearable
        >
          <el-option
            v-for="dict in gw_site_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          ></el-option>
        </el-select>
        <!-- <el-select
          v-model="queryParams.outdoor"
          placeholder="是否室外"
          style="width: 120px"
          clearable 
          @change="handleQuery"
        >
          <el-option label="是" :value="true" />
          <el-option label="否" :value="false" />
        </el-select> -->
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <!-- <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleOnline"
          >未入网网关</el-button
        >
      </el-col> -->
      <!-- <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['system:post:add']"
          >新增网关</el-button
        >
      </el-col> -->
      <!-- <el-col :span="1.5">
            <el-button
               type="success"
               plain
               icon="Edit"
               :disabled="single"
               @click="handleUpdate"
               v-hasPermi="['system:post:edit']"
            >修改</el-button>
         </el-col>
         <el-col :span="1.5">
            <el-button
               type="danger"
               plain
               icon="Delete"
               :disabled="multiple"
               @click="handleDelete"
               v-hasPermi="['system:post:remove']"
            >删除</el-button>
         </el-col>
         <el-col :span="1.5">
            <el-button
               type="warning"
               plain
               icon="Download"
               @click="handleExport"
               v-hasPermi="['system:post:export']"
            >导出</el-button>
         </el-col> -->
      <right-toolbar
        :showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="gatewayLists"
      size="small"
      @selection-change="handleSelectionChange"
    >
      <!-- <el-table-column type="selection" width="55" align="center" /> -->
      <el-table-column label="序号" width="55" type="index" align="center">
        <template #default="scope">
            <span>{{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="网关编号" width="290" align="center" prop="id" /> -->
      <el-table-column label="网关MAC地址" align="center" prop="mac" min-width="120"/>
      <el-table-column
        label="手环连接数量"
        align="center"
        prop="wb_length"
        min-width="100"
      >
        <template #default="scope">
          <el-tag v-if="!scope.row?.wb_length && scope.row?.wb_length !== 0" type="danger">0</el-tag>
          <el-tag v-else="scope.row?.wb_length > 0" :type="Number(scope.row?.wb_length)>100?'success':'primary'">
            {{ scope.row?.wb_length }}
          </el-tag>
          <!-- <el-tag v-if="!scope.row?.last_report_wb_cnt && scope.row?.last_report_wb_cnt !== 0" type="danger">0</el-tag>
          <el-tag v-else="scope.row?.last_report_wb_cnt > 0" :type="Number(scope.row?.last_report_wb_cnt)>100?'success':'primary'">
            {{ scope.row?.last_report_wb_cnt }}
          </el-tag> -->
        </template>
      </el-table-column>
      <el-table-column label="在线时长(s)" align="center" prop="online_time" min-width="190">
        <template #default="scope">
          <!-- <el-tag v-if="scope.row?.online_time"> -->
            {{scope.row?.online_time}} 
          <!-- </el-tag> -->
          <span v-if="scope.row?.online_time">
            ( <span style="color: #67c23a;">{{ formatOnlineTime(scope.row?.online_time, true) }}</span> )
          </span>
          <span v-else> -- </span>
        </template>
      </el-table-column>
      <el-table-column
        label="教育集团名称 / 学校名称 / 班级名称"
        min-width="330"
        align="center"
        prop="class"
      >
        <template #default="scope">
          <el-tag
            v-if="
              scope.row.class?.school?.edgroup?.name
            "
            type="danger"
          >
            {{
              scope.row.class?.school?.edgroup?.name
            }}
          </el-tag>
          <el-tag
            v-if="scope.row.class?.school?.name"
            type="primary"
          >
            {{ scope.row.class?.school?.name }}
          </el-tag>
          <el-tag
            v-if="scope.row.class?.name"
            type="warning"
          >
            {{ scope.row.class?.name }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="温度" align="center" prop="gw_temperature">
        <template #default="scope">
          <b :style="{ color: getTempColor(scope.row?.gw_temperature || 0) }">
            {{ formatTemperature(scope.row.gw_temperature)}}
          </b>
        </template>
      </el-table-column>
      <el-table-column label="固件版本" align="center" prop="version_bin">
        <template #default="scope">
          {{ !scope.row.version_bin ? " -- " : scope.row.version_bin }}/
          {{ !scope.row.version_fs ? " -- " : scope.row.version_fs }}
        </template>
      </el-table-column>
      <!-- <el-table-column label="场景" align="center" prop="scene" /> -->
      <el-table-column label="分布位置" align="center" prop="site" >
        <template #default="scope">
          <dict-tag v-if="scope.row?.site" :options="gw_site_type" :value="scope.row?.site" />
          <span v-else>--</span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="CPU情况" align="center" prop="cpu1" min-width="150">
        <template #default="scope">
          <el-tag  v-if="scope.row?.cpu1" :type="100-Number(scope.row?.cpu1) > 50?'danger':100-Number(scope.row?.cpu1) >= 30?'warning':'success'">
            cpu1: {{ 100-Number(scope.row?.cpu1) || '*'}} %
          </el-tag>
          <el-tag v-if="scope.row?.cpu2" :type="100-Number(scope.row?.cpu2) > 50?'danger':100-Number(scope.row?.cpu2) >= 30?'warning':'success'">
            cpu2: {{ 100-Number( scope.row?.cpu2) || '*'}} %
          </el-tag>
        </template>
      </el-table-column> -->
      <el-table-column label="内存使用" align="center" prop="sram" min-width="150">
        <template #default="scope">
          <el-tooltip :content="`sram: ${scope.row?.sram || '-'}`" placement="top">
            <el-tag
              v-if="scope.row?.sram"
              :type="Number(calcPercent(scope.row.sram)) > 50 ? 'danger' : Number(calcPercent(scope.row.sram)) >= 30 ? 'warning' : 'success'"
            >
              sram: {{ calcPercent(scope.row.sram) }}%
            </el-tag>
          </el-tooltip>
          <el-tooltip :content="`psram: ${scope.row?.psram || '-'}`" placement="top">
            <el-tag
              v-if="scope.row?.psram"
              :type="Number(calcPercent(scope.row.psram)) > 50 ? 'danger' : Number(calcPercent(scope.row.psram)) >= 30 ? 'warning' : 'success'"
            >
              psram: {{ calcPercent(scope.row.psram) }}%
            </el-tag>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column label="上次离线原因" align="center" prop="reset_reason" min-width="120">
        <template #default="scope">
          <dict-tag v-if="scope.row?.reset_reason" :options="gw_reset_reason" :value="scope.row?.reset_reason" />
          <span v-else>--</span>
        </template>
      </el-table-column>
      <!-- <el-table-column
        label="是否室外"
        width="80"
        align="center"
        prop="outdoor"
      >
        <template #default="scope">
          <el-tag v-if="!!scope.row.outdoor" type="primary">是</el-tag>
          <el-tag v-else type="danger">否</el-tag>
        </template>
      </el-table-column> -->
      <!-- <el-table-column label="图片" align="center" prop="photo" /> -->
      <!-- 是否在线 -->
      <el-table-column label="在线时间" align="center" min-width="240">
        <template #default="scope">
          <span v-if="scope.row.time">
            {{scope.row.time}} 
            ( <span style="color: #67c23a;">{{ formatOnlineTime(scope.row.time, false) }}</span> )
          </span>
          <span v-else> -- </span>
        </template>
      </el-table-column>
      <el-table-column
        label="最后上报时间"
        align="center"
        prop="last_report_time"
        min-width="240"
      >
        <template #default="scope">
          <span v-if="scope.row.last_report_time">
            {{scope.row.last_report_time}} 
            ( <span style="color: #67c23a;">{{ formatOnlineTime(scope.row.last_report_time, false) }}</span> )
          </span>
          <span v-else> -- </span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        width="200"
        fixed="right"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-button link type="primary" @click="handleView(scope.row)"
            >查看上报数据</el-button
          >
          <el-dropdown v-if="scope.row?.mac && !/[A-Z]/.test(scope.row?.mac)" style="--el-dropdown-menu-item-hover-bg-color: var(--el-color-primary-light-9);vertical-align: middle;">
            <el-button link type="primary" v-if="scope.row?.mac && !/[A-Z]/.test(scope.row?.mac)">
              <el-icon><DArrowRight /></el-icon> 更多
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item icon="Sunrise" @click="() => handleLight(scope.row, 'red')" style="color: #f56c6c;">红灯</el-dropdown-item>
                <el-dropdown-item icon="Sunrise" @click="() => handleLight(scope.row, 'green')" style="color: #67c23a;">绿灯</el-dropdown-item>
                <el-dropdown-item icon="Sunrise" @click="() => handleLight(scope.row, 'blue')" style="color: #409EFF;">蓝灯</el-dropdown-item>
                <el-dropdown-item icon="Bell" @click="() => handleOperate(scope.row, 'buzzer')" style="color: #e6a23c;">蜂鸣</el-dropdown-item>
                <el-dropdown-item icon="ChromeFilled" @click="() => handleOperate(scope.row, 'telnet')">终端</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 手环详情数据 -->
    <el-dialog :title="title" v-model="open" width="90%" append-to-body :close-on-click-modal="false" :before-close="handleClose">
      <el-row :gutter="20">
        <el-col :span="5" :xs="24">
          <el-card class="box-card">
            <template v-slot:header>
              <div class="clearfix">
                <span>网关信息</span>
              </div>
            </template>
            <div class="list-group-top-none">
              <ul class="list-group list-group-striped">
                <li class="list-group-item">
                  <!-- <svg-icon icon-class="cpu" /> -->
                  <el-icon class="cpu"><plus /></el-icon> MAC地址
                  <div class="pull-right">
                    {{ queryParamsDetail?.current_gw?.mac || "--" }}
                  </div>
                </li>
                <li class="list-group-item">
                  <svg-icon icon-class="number" /> 版本号
                  <div class="pull-right">
                    {{ queryParamsDetail?.current_gw?.version_bin || "--" }}/{{
                      queryParamsDetail?.current_gw?.version_fs || "--"
                    }}
                  </div>
                </li>
                <li class="list-group-item">
                  <svg-icon icon-class="size" /> 统计数量
                  <div class="pull-right">
                    {{
                      queryParamsDetail?.current_gw?.last_report_wb_cnt || "--"
                    }}
                  </div>
                </li>
                <li class="list-group-item">
                  <svg-icon icon-class="time" /> 心跳时间
                  <div class="pull-right">
                    {{ queryParamsDetail?.current_gw?.time || "--" }}
                  </div>
                </li>
              </ul>
            </div>
          </el-card>
        </el-col>
        <el-col :span="19" :xs="24">
          <el-card class="wristbandDetail">
            <template v-slot:header>
              <div class="clearfix">
                <span>手环数据</span>
                <!-- 共查找到<b style="color:#F56C6C">{{ totalDetail || 0 }}</b>条 -->
              </div>
            </template>
            <el-form
              :model="queryParamsDetail"
              ref="queryDetailRef"
              :inline="true"
            >
              <!-- v-show="showSearch" -->
              <el-form-item label="手环MAC地址" prop="wb_mac">
                <el-input
                  v-model="queryParamsDetail.wb_mac"
                  placeholder="请输入手环MAC地址"
                  clearable
                  style="width: 200px"
                  @keyup.enter="handleQueryDetail"
                />
              </el-form-item>
              <el-form-item label="查询时间" prop="time">
                <el-select
                  v-model="queryParamsDetail.time"
                  placeholder="请选查询时间"
                  style="width: 260px"
                >
                  <el-option
                    v-for="dict in time_slot"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  ></el-option>
                </el-select>
              </el-form-item>
              <!-- <el-form-item label="创建时间">
                    <el-date-picker
                      v-model="queryParamsDetail.date"
                      type="datetimerange"
                      range-separator="至"
                      value-format="YYYY-MM-DD HH:mm:ss"
                      start-placeholder="开始日期"
                      end-placeholder="结束日期">
                    </el-date-picker>
                  </el-form-item> -->
              <el-form-item>
                <el-button
                  type="primary"
                  icon="Search"
                  @click="handleQueryDetail"
                  >搜索</el-button
                >
                <el-button icon="Refresh" @click="resetQueryDetail"
                  >重置</el-button
                >
                <el-button :icon="queryParamsDetail.status?'VideoPause':'VideoPlay'" @click="timedQueryDetail"
                  >{{queryParamsDetail.status?'暂停':'开始'}}</el-button
                >
              </el-form-item>
            </el-form>
            <el-table
              v-loading="loadingDetail"
              :data="wristbandDetail"
              size="small"
              @selection-change="handleSelectionChange"
            >
              <!-- <el-table-column label="序号" width="60" type="index" align="center"/> -->
              <el-table-column label="序列号" align="center" prop="idx" fixed="left"/>
              <el-table-column
                label="手环MAC地址"
                width="140"
                align="center"
                prop="mac"
                fixed="left"
              />
              <el-table-column label="心率" align="center" prop="hr">
                <template #default="scope">
                  {{ scope.row.hr }} (
                    <b v-if="scope.row?.fake_hr" style="color:#F56C6C">1</b>
                    <b v-else style="color:#67c23a">0</b> )
                </template>
              </el-table-column>
              <el-table-column label="步数" align="center" prop="steps" >
                <template #default="scope">
                  <b :style="{ color: getStepsColor(scope.row.steps) }">
                    {{ scope.row?.steps || 0 }}
                  </b>
                </template>
              </el-table-column>
              <el-table-column label="运动强度" width="80" align="center" prop="motion">
                <template #default="scope">
                  <b :style="{ color: scope.row?.motion && scope.row?.motion > 0? 'inherit' : '#F56C6C' }">
                    {{ scope.row?.motion ? scope.row.motion.toFixed(6) : 0 }}
                  </b>
                </template>
              </el-table-column>
              <el-table-column label="运动强度方差" width="100" align="center" prop="motion_variance">
                <template #default="scope">
                  <b :style="{ color: scope.row?.motion_variance && scope.row?.motion_variance > 0? 'inherit' : '#F56C6C' }">
                    {{ scope.row?.motion_variance ? scope.row.motion_variance.toFixed(6) : 0 }}
                  </b>
                </template>
              </el-table-column>
              <el-table-column label="温度" align="center" prop="temperature">
                <template #default="scope">
                  <b :style="{ color: getTemperatureColor(scope.row?.temperature) }">
                    {{ scope.row?.temperature || 0 }}
                  </b>
                </template>
              </el-table-column>
              <el-table-column label="区角豆1" align="center" prop="beacon1">
                <template #default="scope">
                  <b :style="{ color: scope.row?.beacon1 && scope.row?.beacon1 > 0? '#67c23a' : '#F56C6C' }">
                    {{ scope.row?.beacon1 || 0 }}
                  </b>
                </template>
              </el-table-column>
              <el-table-column label="区角豆2" align="center" prop="beacon2">
                <template #default="scope">
                  <b :style="{ color: scope.row?.beacon2 && scope.row?.beacon2 > 0? '#67c23a' : '#F56C6C' }">
                    {{ scope.row?.beacon2 || 0 }}
                  </b>
                </template>
              </el-table-column>
              <el-table-column label="区角豆3" align="center" prop="beacon3">
                <template #default="scope">
                  <b :style="{ color: scope.row?.beacon3 && scope.row?.beacon3 > 0? '#67c23a' : '#F56C6C' }">
                    {{ scope.row?.beacon3 || 0 }}
                  </b>
                </template>
              </el-table-column>
              <!-- <el-table-column label="x" align="center" prop="acc_x" />
              <el-table-column label="y" align="center" prop="acc_y" />
              <el-table-column label="z" align="center" prop="acc_z" /> -->
              <el-table-column label="信号" align="center" prop="rssi">
                <template #default="scope">
                  <b :style="{ color: getRssiColor(scope.row?.rssi || 0) }">
                    {{ scope.row?.rssi || '--' }}
                  </b>
                </template>
              </el-table-column>
              <el-table-column label="格式" align="center" prop="format" />
              <el-table-column
                label="网关MAC地址"
                width="140"
                align="center"
                prop="gw_mac"
                sortable
                fixed="right"
              />
              <el-table-column
                label="时间"
                align="center"
                prop="time"
                min-width="190"
                sortable
                fixed="right"
              >
                <template #default="scope">
                  <!-- {{ scope.row.time ? formartIOSDate(scope.row.time) : "--" }} -->
                  <span v-if="scope.row.time">
                    {{scope.row.time || '--'}} 
                    ( <span style="color: #67c23a;">{{ formatOnlineTime(scope.row.time) }}</span> )
                  </span>
                  <span v-else> -- </span>
                </template>
              </el-table-column>
            </el-table>
            <pagination
              v-show="totalDetail > 0"
              :layout="'total, sizes, prev, pager, next'"
              :total="totalDetail"
              :small="true"
              v-model:page="queryParamsDetail.pageNum"
              v-model:limit="queryParamsDetail.pageSize"
              @pagination="getWristbandDetails"
              style="max-width: 100%; margin: 0 auto"
            />
          </el-card>
        </el-col>
      </el-row>
      <template #footer>
        <div class="dialog-footer">
          <!-- <el-button type="primary" @click="submitForm">确 定</el-button> -->
          <el-button @click="cancelDetail">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Post">
import { getCurrentInstance } from 'vue'

import {
  getGatewayListWb,
  getGatewayListByMAC,
} from "@/api/system/firmware/gateway";
import { getClassList, getClassGwControlLed } from "@/api/system/school/class";
import { getSchoolList } from "@/api/system/school/school";
import { getEdgroupList } from "@/api/system/school/edgroup";
import { reactive } from "vue";
import { getAuthRole } from "@/api/system/user";
import { getCurrentDayDate, formartIOSDate } from "@/utils/dateFormart";
import { formatDate, formatSeconds } from '@/utils/dateFormart';

const { proxy } = getCurrentInstance();
const { time_slot, gw_site_type, gw_reset_reason } = proxy.useDict(
  "time_slot", "gw_site_type", "gw_reset_reason"
);
const EdgroupList = ref();
const schoolList = ref([]);
const classList = ref([]);
const gatewayLists = ref([]);
const open = ref(false);
const openWristband = ref(false);
const wristbandList = ref([]);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const titleWristband = ref("");
const wristbandDetail = ref([]);
const refreshTimer = ref(null);
const isFetching = ref(false);
let intervalId = null;

onMounted(() => {
  // loading.value = true;
  initData();
  intervalId = setInterval(() => {
    // loading.value = true;
    getList();
  }, 1500);
});

onUnmounted(() => {
  if (intervalId) {
    clearInterval(intervalId);
  }
});
// 判断是否是新网关的方法
const isNewGateway = (mac) => {
  // 检查mac地址是否包含大写字母或者冒号
  return mac && !/[A-Z:]/.test(mac);
};
const getTempColor = (temperature) => {
  if (temperature && temperature > 60) {
    return '#F56C6C';
  } else if (temperature && temperature >= 50) {
    return '#E6A23C';
  } else if (temperature && temperature >= -10) {
    return '#67c23a';
  } else {
    return '#999999'; // 默认颜色
  }
};
function calcPercent(val) {
  if (!val || typeof val !== 'string' || !val.includes('/')) return '--';
  const [used, total] = val.split('/').map(v => Number(v.trim()));
  if (!used || !total) return '--';
  return ((used / total) * 100).toFixed(1);
}
function formatTemperature(val) {
  if(!val){
    return '--'
  }
  const str = String(val);
  const idx = str.indexOf('.');
  if (idx === -1) return str;
  return str.substring(0, idx + 2); // 保留到小数点后一位，不四舍五入
}
// 定义 formatOnlineTime 方法
const formatOnlineTime = (time, status) => {
  if (!time) {
    return ' -- ';
  }
  const countTime = status ? formatSeconds(time) : formatDate(time);
  return countTime || ' -- ';
};
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 20,
    mac: undefined,
    edgroup_id: undefined,
    school_id: undefined,
    class_id: undefined,
    outdoor: undefined,
    // version: undefined,
    // date: getCurrentDayDate('yyddmm')||''//[],
  },
  rules: {},
});

const { queryParams, form, rules } = toRefs(data);
const dataDetail = reactive({
  loadingDetail: false,
  queryParamsDetail: {
    pageNum: 1,
    pageSize: 15,
    // date: [],
    current_gw: undefined,
    wb_mac: undefined,
    gw_mac: undefined,
    last_report_time: undefined,
    time: undefined,
    status: false
  },
  totalDetail: 0,
});
const { queryParamsDetail, loadingDetail, totalDetail } = toRefs(dataDetail);
function rawChange(val) {
  if (!val) {
  }
}

const wrisbandData = reactive({
  formWrisband: {},
  idsWrisband: [],
  loadingWrisband: false,
  queryParamsWrisband: {
    pageNum: 1,
    pageSize: 10,
    mac: undefined,
  },
});

const { idsWrisband, queryParamsWrisband } = toRefs(wrisbandData);

// 定义计算步数颜色的方法
const getStepsColor = (steps) => {
  if (steps && steps > 4500) {
    return '#67c23a';
  } else if (steps && steps > 0) {
    return 'inherit';
  } else {
    return '#F56C6C';
  }
};
const getTemperatureColor = (temperature) => {
  if (temperature && temperature > 37.5) {
    return '#F56C6C';
  } else if (temperature && temperature >= 35.5) {
    return '#67c23a';
  } else {
    return '#E6A23C';
  }
};
const getRssiColor = (rssi) => {
  if (rssi && rssi > -40) {
    return '#67c23a';
  } else if (rssi && rssi >= -80) {
    return '#E6A23C';
  } else {
    return '#F56C6C';
  }
};
/** 查询网关列表 */
function getList() {
  if (isFetching.value) return;
  isFetching.value = true;
  console.log("网关实时列表 入参 params", queryParams.value);
  getGatewayListWb(queryParams.value)
    .then((response) => {
      console.log("网关实时列表", response.data);
      gatewayLists.value = response.data.data || [];
      total.value = response.data.total || 0
    })
    .finally(() => {
      isFetching.value = false;
      loading.value = false;
    });
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  loading.value = true;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  // dateRange.value = [];
  proxy.resetForm("queryRef");
  handleQuery();
}

/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 手环多选框选中数据 */
function handleSelectionWristbandChange(selection) {
  idsWrisband.value = selection.map((item) => item.mac);
}

/** 查看按钮操作 */
function handleView(row) {
  console.log("current_gw", row);
  queryParamsDetail.value.current_gw = row;
  queryParamsDetail.value.gw_mac = row.mac;
  queryParamsDetail.value.time = "300000";
  queryParamsDetail.value.wb_mac = undefined;
  queryParamsDetail.value.pageNum = 1;
  queryParamsDetail.value.pageSize = 15;
  queryParamsDetail.value.status = false
  idsWrisband.value = [];
  // 获取手环数据
  resetDetail();
  // 先清除之前的定时器
  if (refreshTimer.value) {
    console.log("show 清除定时器");
    clearInterval(refreshTimer.value);
    refreshTimer.value = null;
  }
  // 立即获取一次数据
  getWristbandDetails();
  // queryParamsDetail.value.status = true
  // // 设置定时器，每1秒刷新一次
  // refreshTimer.value = setInterval(() => {
  //   getWristbandDetails();
  // }, 1000);
  openWristband.value = true;
  titleWristband.value = "网关在线手环数据";
}
/** 获取手环详情 */
function getWristbandDetails() {
  // loading.value = true;
  // loadingDetail.value = true;
  open.value = true;
  title.value = "手环详情";
  console.log("获取手环详情入参: ", queryParamsDetail.value);
  getGatewayListByMAC(queryParamsDetail.value).then((response) => {
    console.log("获取手环详情", response);
    if (response.code === 200) {
      wristbandDetail.value = response.data.data;
      totalDetail.value = response.data.total;
    } else {
      wristbandDetail.value = [];
      totalDetail.value = 0;
      // loadingDetail.value = false;
    }
  }).finally(() => {
    loadingDetail.value = false;
  });
}
/** 详情close按钮 */
function handleClose() {
  // 清除定时器
  if (refreshTimer.value) {
    console.log("close 清除定时器");
    clearInterval(refreshTimer.value);
    refreshTimer.value = null;
    queryParamsDetail.value.status = false
  }
  open.value = false;
  resetDetail();
}
/** 详情取消按钮 */
function cancelDetail() {
  // 清除定时器
  if (refreshTimer.value) {
    console.log("cancel 清除定时器");
    clearInterval(refreshTimer.value);
    refreshTimer.value = null;
    queryParamsDetail.value.status = false
  }
  open.value = false;
  resetDetail();
}

/** 详情表单重置 */
function resetDetail() {
  // proxy.resetForm("wristbandRef");
}

/** 详情搜索按钮操作 */
function handleQueryDetail() {
  queryParamsDetail.value.pageNum = 1;
  getWristbandDetails();
}

/** 详情重置按钮操作 */
function resetQueryDetail() {
  // dateRange.value = [];
  proxy.resetForm("queryDetailRef");
  handleQueryDetail();
}
/** 详情开始暂停按钮操作 */
function timedQueryDetail() {
  if(queryParamsDetail.value.status){
    console.log("暂停 清除定时器");
    clearInterval(refreshTimer.value);
    queryParamsDetail.value.status = false
    return
  } else{
    // 先清除之前的定时器
    if (refreshTimer.value) {
      console.log("show 清除定时器");
      clearInterval(refreshTimer.value);
      refreshTimer.value = null;
    }
    // 立即获取一次数据
    getWristbandDetails();
    queryParamsDetail.value.status = true
    // 设置定时器，每1秒刷新一次
    refreshTimer.value = setInterval(() => {
      getWristbandDetails();
    }, 1000);
    queryParamsDetail.value.status = true
  }
  // queryParamsDetail.value.status = !queryParamsDetail.value.status
}
function handleOperate(row, type) {
  if(type == 'buzzer'){
    // 蜂鸣器操作
    proxy.$modal.msgError("蜂鸣器操作即将开放");
    return
  }
  if(type == 'telnet'){
    // 生成 32位长度数字+字母的token，用于连接BeConsole
    const token = Math.random().toString(36).substring(2, 34);
    getClassGwControlLed({
      action: "telnet",
      gw_mac: row.mac,
      token: token,
      // url: `wss://beconsole-proxy.zhiyu.school/device?token=${token}`,
    }).then((res) => {
      console.log("等待连接BeConsole res", res);
      proxy.$modal.msgSuccess("连接BeConsole");
      // 打开BeConsole
      window.open(`https://beconsole.become.cool/?connType=ws&connUrl=wss://beconsole-proxy.zhiyu.school/terminal?token=${token}`);
    });
  }
}
function handleLight(row, color) {
  console.log("闪灯 选择", row, color);
  const colorValue = color === 'red' ? {
    red: 1,// 0-255, 0:不亮, 255需转1因为硬件暂不支持
    green: 0,
    blue: 0,
  } : color === 'green' ? {
    red: 0,
    green: 1,
    blue: 0,
  } : color === 'blue' ? {
    red: 0,
    green: 0,
    blue: 1,
  } : {
    red: 1,
    green: 1,
    blue: 1,
  };
  console.log("闪灯 入参 ", {
    action: "led",
    gw_mac: row.mac,
    led1: colorValue});
  getClassGwControlLed({
    action: "led",
    gw_mac: row.mac,
    led1: colorValue,
  }).then((res) => {
    console.log("闪灯 res", res);
    proxy.$modal.msgSuccess("闪灯成功");
  });
}
// getList();
// 切换教育集团
function changeQueryEdgroup() {
  queryParams.value.school_id = null;
  schoolList.value = [];
  let params = {
    id: queryParams.value.edgroup_id,
  };
  getSchoolList(params).then((res) => {
    schoolList.value = res.data.data.map((item) => {
      return {
        label: item.name,
        value: item.id,
        photo: item.photo,
      };
    });
  });
}
// 切换学校
function changeQuerySchool() {
  queryParams.value.class_id = null;
  classList.value = [];
  let params = {
    school_id: queryParams.value.school_id,
  };
  // console.log('params', params)
  getClassList(params).then((res) => {
    // console.log("班级列表", res.data.data);
    classList.value = res.data.data.map((item) => {
      return {
        label: item.name,
        value: item.id,
        photo: item.photo,
      };
    });
  });
}
function initData(){
  getEdgroupList().then((res) => {
    EdgroupList.value = res.data.data.map((item) => {
      return {
        label: item.name,
        value: item.id,
        photo: item.photo,
      };
    });
  });
  getSchoolList().then((res) => {
    schoolList.value = res.data.data.map((item) => {
      return {
        label: item.name,
        value: item.id,
        photo: item.photo,
      };
    });
  });
  getClassList().then((res) => {
    classList.value = res.data.data.map((item) => {
      return {
        label: item.name,
        value: item.id,
        photo: item.photo,
      };
    });
  });
  getList();
}
</script>
<style lang="scss" scoped>
.list-group-top-none .list-group-striped > .list-group-item {
  border-top: none;
}
.wristbandDetail {
  :deep(.pagination-container .el-pagination) {
    right: 20px;
  }
}
</style>
